//
//  RegisterViewController.m
//  SDKUI
//
//  Created by aiquantong on 17/08/2017.
//  Copyright © 2017 aiquantong. All rights reserved.
//

#import "RegisterViewController.h"
#import "SupportViewController.h"

#import "CCKitManger.h"

#import "HUDUtils.h"
#import "UIAlertUtil.h"
#import "NSString+Check.h"


@interface RegisterViewController ()
{
    NSDate *startDate;
    NSTimer *timer;
}

@property (nonatomic, strong) IBOutlet UITextField *nameTextField;
@property (nonatomic, strong) IBOutlet UIView *nameView;

@property (nonatomic, strong) IBOutlet UITextField *mailTextField;
@property (nonatomic, strong) IBOutlet UIView *mailView;

@property (nonatomic, strong) IBOutlet UITextField *psdTextField;
@property (nonatomic, strong) IBOutlet UIView *psdView;

@property (nonatomic, strong) IBOutlet UIView *registerNameView;


@property (nonatomic, strong) IBOutlet UITextField *phoneTextField;
@property (nonatomic, strong) IBOutlet UIView *phoneView;

@property (nonatomic, strong) IBOutlet UITextField *smsTextField;
@property (nonatomic, strong) IBOutlet UIView *smsView;

@property (nonatomic, strong) IBOutlet UIButton *sendSmsButton;

@property (nonatomic, strong) IBOutlet UIView *registerPhoneView;

@end


@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
        
    self.nameView.layer.borderColor = [UIColor whiteColor].CGColor;
    self.mailView.layer.borderColor = [UIColor whiteColor].CGColor;
    self.psdView.layer.borderColor = [UIColor whiteColor].CGColor;
    
    self.phoneView.layer.borderColor = [UIColor whiteColor].CGColor;
    self.smsView.layer.borderColor = [UIColor whiteColor].CGColor;
}


-(IBAction)onclickSegment:(id)sender
{
    UISegmentedControl *sc = (UISegmentedControl *)sender;
    if (sc.selectedSegmentIndex == 0) {
        [self.registerNameView setHidden:NO];
        [self.registerPhoneView setHidden:YES];
    }else{
        [self.registerNameView setHidden:YES];
        [self.registerPhoneView setHidden:NO];
    }
}


-(void)startTimer
{
    startDate = [NSDate date];
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeCallback:) userInfo:nil repeats:YES];
    [timer fire];
}

-(void)stopTimer
{
    if (timer) {
        [timer invalidate];
    }
    timer = nil;
}


-(void)timeCallback:(id)sender
{
    NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:startDate];
    NSTimeInterval remainTime = 120 - timeInterval;
    [self.sendSmsButton setTitle:[NSString stringWithFormat:@"%dS",(int)remainTime] forState:UIControlStateDisabled];
    if (timeInterval < 1) {
        [self stopTimer];
        [self.sendSmsButton setEnabled:YES];
    }
}


-(IBAction)onclickSendMsg:(id)sender
{
    NSString *phoneStr = self.phoneTextField.text;
    if (![phoneStr isValidChinesePhone]) {
        [HUDUtils showHUDTxtOnWindowWithText:@"请输入正确的手机号" hiddenAfter:2];
        return;
    }
    [self.view endEditing:YES];
    
    [CCKitManger requestCodeBySMSCN:phoneStr callback:^(NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error) {
                [HUDUtils showHUDTxtOnWindowWithText:@"短息发送失败" hiddenAfter:2];
            }else{
                [self startTimer];
                [self.sendSmsButton setEnabled:NO];
                [HUDUtils showHUDTxtOnWindowWithText:@"短息发送成功" hiddenAfter:2];
            }
        });
    }];
}


-(IBAction)onclickRegisterPHone:(id)sender
{
    NSString *phoneStr = self.phoneTextField.text;
    NSString *smsStr = self.smsTextField.text;
    [self.view endEditing:YES];
    
    [HUDUtils showHUDOnWindowWithText:@"正在注册.."];
    [CCKitManger validate:smsStr
              phoneNumber:phoneStr
                 callback:^(NSError *error, KandyUserInfo *userInfo) {
                     dispatch_async(dispatch_get_main_queue(), ^{
                         [HUDUtils hideHUDForWindow];
                         if (error) {
                             [HUDUtils showHUDTxtOnWindowWithText:@"注册失败" hiddenAfter:2];
                         }else{
                             [UIAlertUtil
                              showAlertWithPersentViewController:self
                              alertCallBack:^(NSInteger index) {
                                  if (index == 1) {
                                      [HUDUtils showHUDOnWindowWithText:@"正在登录.."];
                                      [CCKitManger
                                       loginKandyWithUserName:userInfo.userId
                                       password:userInfo.password
                                       callback:^(NSError *error) {
                                           dispatch_async(dispatch_get_main_queue(), ^{
                                               [HUDUtils hideHUDForWindow];
                                               if (error) {
                                                   [HUDUtils showHUDTxtOnWindowWithText:@"登录失败" hiddenAfter:3];
                                               }else{
                                                   SupportViewController *mvc = [[SupportViewController alloc] initWithNibName:@"SupportViewController" bundle:nil];
                                                   [self.navigationController setViewControllers:@[mvc] animated:YES];
                                               }
                                           });
                                       }];
                                  }
                              }
                              title:@"注册成功"
                              message:[NSString stringWithFormat:@"用户名：%@\n 密码：%@\n是否登录？",userInfo.userId,userInfo.password]
                              cancelButtonTitle:@"取消"
                              otherButtonTitles:@"确定",nil];
                         }
                     });
                 }];
}



-(IBAction)onclickRegisterName:(id)sender
{
    NSString *nameStr = self.nameTextField.text;
    if (nameStr == nil || nameStr.length < 6 || ![nameStr isValidLetterAndNum]) {
        [HUDUtils showHUDTxtOnWindowWithText:@"用户名为大于6位数字或字母" hiddenAfter:2];
        return;
    }
    
    NSString *mailStr = self.mailTextField.text;
    if (mailStr == nil || ![mailStr isValidateEmail]) {
        [HUDUtils showHUDTxtOnWindowWithText:@"邮箱格式不正确" hiddenAfter:2];
        return;
    }
    
    NSString *pwdStr = self.psdTextField.text;
    if (pwdStr == nil || ![pwdStr isValidatePassword]) {
        [UIAlertUtil showAlertWithTitle:@"提示" message:@"密码为8-20位，含有数字字母大小写" persentViewController:self];
        return;
    }
    
    [self.view endEditing:YES];
    
    [HUDUtils showHUDOnWindowWithText:@"正在注册.."];
    [[CCKitManger shareInstance]
     registerNewUserWithUserId:nameStr
     mail:mailStr
     password:pwdStr
     callback:^(NSError *error, NSDictionary *dic) {
         dispatch_async(dispatch_get_main_queue(), ^{
             [HUDUtils hideHUDForWindow];
             if (error) {
                 [HUDUtils showHUDTxtOnWindowWithText:[error description] hiddenAfter:2];
             }else{
                 [UIAlertUtil
                  showAlertWithPersentViewController:self
                  alertCallBack:^(NSInteger index) {
                      if (index == 1) {
                          [HUDUtils showHUDOnWindowWithText:@"正在登录.."];
                          [CCKitManger
                           loginKandyWithUserName:dic[@"full_user_id"]
                           password:dic[@"user_password"]
                           callback:^(NSError *error) {
                               dispatch_async(dispatch_get_main_queue(), ^{
                                   [HUDUtils hideHUDForWindow];
                                   if (error) {
                                       [HUDUtils showHUDTxtOnWindowWithText:@"登录失败" hiddenAfter:3];
                                   }else{
                                       SupportViewController *mvc = [[SupportViewController alloc] initWithNibName:@"SupportViewController" bundle:nil];
                                       [self.navigationController setViewControllers:@[mvc] animated:YES];
                                   }
                               });
                           }];
                      }
                  }
                  title:@"注册成功"
                  message:[NSString stringWithFormat:@"用户名：%@\n 密码：%@\n是否登录？",dic[@"full_user_id"],dic[@"user_password"]]
                  cancelButtonTitle:@"取消"
                  otherButtonTitles:@"确定",nil];
             }
         });
     }];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)dealloc
{
    [self stopTimer];
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
